package com.example.agriapp.view.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.agriapp.adapter.ArticleAdapter;
import com.example.agriapp.base.BaseFragment;
import com.example.agriapp.R;
import com.example.agriapp.model.bean.Article;
import com.example.agriapp.model.bean.LoseWeightBean;
import com.example.agriapp.util.OkHttpTool;
import com.example.agriapp.adapter.LoseWeightAdapter;
import com.example.agriapp.view.activity.AddProductActivity;
import com.example.agriapp.view.activity.MainActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AgriTechFragment extends BaseFragment {
    private RecyclerView recyclerView;
    private LoseWeightAdapter mNewsAdapter;
    private TabLayout tabLayout;
    private Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private List<Article> articleList = new ArrayList<>();
    private FloatingActionButton fabAdd;
    private ArticleAdapter articleAdapter;


    public static AgriTechFragment newInstance() {
        return new AgriTechFragment();
    }
    
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_agri_tech;
    }
    
    @Override
    protected void initView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        tabLayout = view.findViewById(R.id.tabLayout);
        fabAdd = view.findViewById(R.id.fab_add);
        // 添加标签
        tabLayout.addTab(tabLayout.newTab().setText("热点新闻"));
        tabLayout.addTab(tabLayout.newTab().setText("专家咨询"));
        tabLayout.addTab(tabLayout.newTab().setText("支农宝新闻"));
        tabLayout.addTab(tabLayout.newTab().setText("创业项目"));

        setupTabAppearance(tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 更新选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(true);
                }

                // 根据选中的Tab加载数据
                switch (tab.getPosition()) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 更新未选中状态
                if (tab.getCustomView() != null) {
                    tab.getCustomView().setSelected(false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // Tab被重新选中时的处理（可选）
            }
        });
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        //=1.3、设置recyclerView的布局管理器
        //==2、实例化适配器
        //=2.1、初始化适配器
        // 设置添加按钮点击事件
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddProductActivity.class);
            startActivityForResult(intent, 1);
        });
        prepareDemoData();
        articleAdapter = new ArticleAdapter(articleList, getContext());
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(articleAdapter);
       // loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Article newArticle = (Article) data.getSerializableExtra("newArticle");
            if (newArticle != null) {
                articleList.add(0, newArticle); // 添加到列表顶部
                articleAdapter.notifyItemInserted(0);
                recyclerView.smoothScrollToPosition(0);
            }
        }
    }
    private void prepareDemoData() {
        articleList.add(new Article(
                "101",
                "优质大米种植技术与市场分析",
                "https://img1.baidu.com/it/u=203289247,4110398042&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
                "<p>优质大米是农业生产中的重要作物，种植技术直接影响产量和品质。</p>" +
                        "<p>主要特点包括：</p>" +
                        "<ul>" +
                        "<li>需水量大，适宜水田种植</li>" +
                        "<li>生长周期约120-150天</li>" +
                        "<li>对土壤肥力要求较高</li>" +
                        "</ul>",
                "2023-06-10"
        ));

        articleList.add(new Article(
                "102",
                "有机蔬菜种植全程指导",
                "https://img0.baidu.com/it/u=3992557947,1572072211&fm=253&fmt=auto&app=120&f=JPEG?w=1067&h=800",
                "<p>有机蔬菜种植遵循自然规律，不使用化学合成物质。</p>" +
                        "<p>关键技术要点：</p>" +
                        "<ul>" +
                        "<li>选择抗病性强的品种</li>" +
                        "<li>采用轮作方式防止病虫害</li>" +
                        "<li>使用有机肥料改良土壤</li>" +
                        "</ul>",
                "2023-06-05"
        ));

        articleList.add(new Article(
                "103",
                "苹果园科学管理手册",
                "https://img0.baidu.com/it/u=860617146,3540874593&fm=253&fmt=auto&app=120&f=JPEG?w=566&h=500",
                "<p>苹果种植需要精细化管理才能获得优质高产。</p>" +
                        "<p>管理要点：</p>" +
                        "<ul>" +
                        "<li>合理修剪保持树形</li>" +
                        "<li>花期授粉技术应用</li>" +
                        "<li>病虫害综合防治</li>" +
                        "</ul>",
                "2023-05-28"
        ));

        articleList.add(new Article(
                "104",
                "生猪养殖现代化技术",
                "https://cdn.yangzhu360.com/2024/1125/bcffd90c2ab7e6ef7dd780b5f5bf8a41ea3bee16.png",
                "<p>现代化生猪养殖提高生产效率的同时保障食品安全。</p>" +
                        "<p>主要措施：</p>" +
                        "<ul>" +
                        "<li>自动化饲喂系统</li>" +
                        "<li>环境智能控制系统</li>" +
                        "<li>疫病防控体系</li>" +
                        "</ul>",
                "2023-05-20"
        ));

        articleList.add(new Article(
                "105",
                "茶叶采摘与加工工艺",
                "https://img0.baidu.com/it/u=2051292446,1756980211&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1722",
                "茶叶品质取决于采摘标准和加工工艺。" +
                        "关键环节：" +
                        "" +
                        "适时采摘嫩芽" +
                        "控制萎凋程度" +
                        "精准掌握发酵时间" +
                        "",
                "2023-05-15"
        ));
    }
    @Override
    protected void initData() {
        // 数据初始化在initView中完成
    }

//    private void loadData(){
//        String url="http://v.juhe.cn/toutiao/index";
//        Map<String, Object> map=new HashMap<>();
//        map.put("type","jiankang");
//        map.put("page",1);
//        map.put("page_size",1000);
//        map.put("key","e3399a2c4d23ae4d3f97f27959d1fa6e");
//        //map.put("key","27bb0b0691754637e1ef40bf25f806ff");
//        OkHttpTool.httpGet(url, map, new OkHttpTool.ResponseCallback() {
//            @Override
//            public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (isSuccess && responseCode==200){
//                            try {
//                                JSONObject jsonObject=new JSONObject(response);
//                                String result=jsonObject.getString("result");
//                                JSONObject jsonResult=new JSONObject(result);
//                                String data=jsonResult.getString("data");
//                                Type type=new TypeToken<List<LoseWeightBean>>(){}.getType();//列表信息
//                                List<LoseWeightBean> list=gson.fromJson(data,type);
//                                if (list.size() > 0){
//                                    mNewsAdapter.addItem(list);
//                                }
//                                Toast.makeText(getActivity(),"加载成功", Toast.LENGTH_SHORT).show();
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                });
//            }
//        });
//    }

    private void setupTabAppearance(TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                TextView tabView = new TextView(getContext());
                tabView.setText(tab.getText());
                tabView.setGravity(Gravity.CENTER);
                tab.setCustomView(tabView);
            }
        }

        // 默认选中第一个Tab
        TabLayout.Tab firstTab = tabLayout.getTabAt(0);
        if (firstTab != null && firstTab.getCustomView() != null) {
            firstTab.getCustomView().setSelected(true);
        }
    }
}